$(document).ready(function(){
    var columnid = $("#hidd_columnid").val();
    var specialid = $("#hidd_specialid").val();
    var mainphoto = $("#hidd_mainphoto").val();
    
    if (columnid != "" || specialid != "") {
        $(".attachment").show();
        $("input[@type=radio][value='" + mainphoto + "']").attr("checked", true);
		if(columnid != ""){
       		$("#columnid").val(columnid);
		}
		if(specialid != ""){
       		$("#specialid").val(specialid);
		}
    }
    $('textarea.tinymce').tinymce({
        width: "97.5%",
        height: "500",
        script_url: '../js-plugin/tiny_mce/tiny_mce.js',
        skin: "o2k7",
        skin_variant: "silver",
        language: "zh-cn",
        theme: "advanced",
        plugins: "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
        
        theme_advanced_buttons1: "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,|,link,unlink,anchor,image,cleanup,help,code,|,fullscreen,print,preview",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,insertdate,inserttime,|,forecolor,backcolor,|,insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs",
        theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,ltr,rtl",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true,
        content_css: "../style/master/editor.css",
        // update validation status on change
        onchange_callback: function(editor){
            tinyMCE.triggerSave();
            $("#" + editor.id).valid();
        }
        
    });
    // upload	
    var uploader = '../js-plugin/uploadify/uploadify_cn.swf';
    var images_script = "/action/master/ArticleImageUpload";
    var files_script = "/action/master/ArticleFileUpload";
    var cancelImg = '../js-plugin/uploadify/cancel.png';
    var folder = '/upload';
    var identifies = {
        'identifies': $("#identifies").val()
    };
    $('#images_file').uploadify({
        'uploader': uploader,
        'script': images_script,
        'cancelImg': cancelImg,
        'scriptData': identifies,//解决firefox 的session bug
        'folder': folder,
        'auto': true,
        'multi': true,
        'fileExt': '*.jpg;*.gif;*.png;*.bmp',
        'fileDesc': '请选择图片文件 (.JPG, .GIF, .PNG, .BMP)',
        'queueID': 'custom-queue',
        'buttonText': "选择上传图片",
        'removeCompleted': true,
        'onComplete': function(e, queueId, fileObj, response, data){
            //console.log(response);
            var obj = $.parseJSON(response);
            if (obj.success) {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: fileObj.name + " 上传成功"
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
                tinyMCE.execCommand("mceReplaceContent", false, "<img src=\"" + obj.filepath + "\">");
                $(".attachment").show();
                var templateTr = $("#photo-preview-tpl").children("li").clone().show();
                templateTr.find("img").attr("src", obj.filepath);
                templateTr.find("a").attr("href", obj.fileid);
                templateTr.find("a").click(delphotoClickHandler).easyconfirm({
                    locale: {
                        title: '操作确认',
                        button: ['取消', '是的，确定删除']
                    }
                });
                templateTr.find("input").val(obj.filepath);
                $('#photo-preview').append(templateTr);
                
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: obj.message
                });
                $(".loadingbox").delay(3000).fadeOut(600);
                $('#status-message').append("<li>" + obj.message + "</li>");
            }
        }
        
    });
    var delphotoClickHandler = function(){
        var tmp = $(this);
        var tmpid = tmp.attr("href");
        
        $.post("/action/master/deleteArticlePhoto", {
            Action: "post",
            id: tmpid
        }, function(data, textStatus){
            if (!data.success) {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: data.message
                });
                $(".loadingbox").delay(3000).fadeOut(600);
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: data.message
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
                tmp.parents("li").hide(2000, function(){
                    tmp.parents("li").remove();
                });
            }
        }, "json");
    };
    $(".delphoto").click(delphotoClickHandler).easyconfirm({
        locale: {
            title: '操作确认',
            button: ['取消', '是的，确定删除']
        }
    });
    
    $('#attachment_file').uploadify({
        'uploader': uploader,
        'script': files_script,
        'scriptData': identifies,//解决firefox 的session bug
        'cancelImg': cancelImg,
        'folder': folder,
        'auto': true,
        'multi': true,
        'fileExt': '*.*',
        'fileDesc': '请选择文件',
        'queueID': 'custom-queue',
        'buttonText': "选择上传附件",
        'removeCompleted': true,
        'onComplete': function(e, queueId, fileObj, response, data){
            var obj = $.parseJSON(response);
            if (obj.success) {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: fileObj.name + " 上传成功"
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
                $(".attachment").show();
                var templateTr = $("#attachment-preview-tpl").children("li").clone(true).show();
                templateTr.find("a").attr("href", obj.fileid);
                templateTr.find("a").click(delFileClickHandler).easyconfirm({
                    locale: {
                        title: '操作确认',
                        button: ['取消', '是的，确定删除']
                    }
                });
                templateTr.find("b").text(obj.originalnames);
                $('#attachment-preview').append(templateTr);
                
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: obj.message
                });
                $(".loadingbox").delay(3000).fadeOut(600);
                $('#status-message').append("<li>" + obj.message + "</li>");
            }
        }
        
    });
    
    $('#midea_file').uploadify({
        'uploader': uploader,
        'script': files_script,
        'scriptData': identifies,//解决firefox 的session bug
        'cancelImg': cancelImg,
        'folder': folder,
        'auto': true,
        'multi': true,
        'fileExt': '*.avi;*.wmv;*.mpg;*.rm;*.rmvb;*.swf',
        'fileDesc': '请选择媒体文件 (.AVI, .WMV, .MPG, .RM, .RMVB, .SWF)',
        'queueID': 'custom-queue',
        'buttonText': "选择媒体附件",
        'removeCompleted': true,
        'onComplete': function(e, queueId, fileObj, response, data){
            var obj = $.parseJSON(response);
            if (obj.success) {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: fileObj.name + " 上传成功"
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
                if (fileObj.type == ".swf") {
                    tinyMCE.execCommand("mceReplaceContent", false, "<object width=\"320\" height=\"240\" data=\"123\" type=\"application/x-shockwave-flash\"><param name=\"src\" value=\"" + obj.filepath + "\" /></object>");
                }
                if (fileObj.type == ".avi" || fileObj.type == ".wmv" || fileObj.type == ".mpg") {
                    tinyMCE.execCommand("mceReplaceContent", false, "<object width=\"320\" height=\"240\" data=\"123\" type=\"application/x-mplayer2\"><param name=\"src\" value=\"" + obj.filepath + "\" /></object>");
                }
                if (fileObj.type == ".rm" || fileObj.type == ".rmvb") {
                    tinyMCE.execCommand("mceReplaceContent", false, "<object width=\"320\" height=\"240\" data=\"123\" type=\"audio/x-pn-realaudio-plugin\"><param name=\"src\" value=\"" + obj.filepath + "\" /></object>");
                }
                
                $(".attachment").show();
                var templateTr = $("#attachment-preview-tpl").children("li").clone(true).show();
                templateTr.find("a").attr("href", obj.fileid);
                templateTr.find("a").click(delFileClickHandler).easyconfirm({
                    locale: {
                        title: '操作确认',
                        button: ['取消', '是的，确定删除']
                    }
                });
                templateTr.find("b").text(obj.originalnames);
                $('#attachment-preview').append(templateTr);
                
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: obj.message
                });
                $(".loadingbox").delay(3000).fadeOut(600);
                
                $('#status-message').append("<li>" + obj.message + "</li>");
            }
        }
    });
    
    var delFileClickHandler = function(e){
        var tmp = $(e.currentTarget);
        var tmpid = tmp.attr("href");
        $.post("/action/master/deleteArticleFile", {
            Action: "post",
            id: tmpid
        }, function(data, textStatus){
            if (!data.success) {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: obj.message
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(3000).fadeOut(600);
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: data.message
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
                tmp.parents("li").hide("slide", {
                    direction: "left"
                }, 1000).delay(1000).remove();
            }
        }, "json");
    };
    
    $(".resetBtn").click(function(){
        $("#articleEditor").resetForm();
        return false;
    }).easyconfirm({
        locale: {
            title: '操作确认',
            button: ['取消', '是的，确定重置']
        }
    });
    
    
    $(".saveBtn").click(function(){
        var columnid = $("#columnid").val();
        var specialid = $("#specialid").val();
        if ((specialid == null || specialid == "" || specialid == -1) &&
        (columnid == null || columnid == "" || columnid == -1)) {
            alert('请选择所属栏目或所属专题');
        }
        else {
            tinyMCE.triggerSave();
            $("#articleEditor").submit();
        }
        return false;
    })
    $("#postdate").datepicker({
        dateFormat: 'yy-mm-dd'
    }).attr("readonly", true);
    
    
    /**  表单提交 **/
    // 中文字两个字节       
    jQuery.validator.addMethod("byteRangeLength", function(value, element, param){
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) ||
        (length >= param[0] && length <= param[1]);
    }, "请确保输入的值在3-15个字节之间(一个中文字算2个字节)");
    jQuery.validator.addMethod("isDate", function(value, element){
        var ereg = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})$/;
        var r = value.match(ereg);
        if (r == null) {
            return false;
        }
        var d = new Date(r[1], r[3] - 1, r[5]);
        var result = (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[5]);
        return this.optional(element) || (result);
    }, "请输入正确的日期");
    
    $("#articleEditor").validate({
        submitHandler: function(form){
            var tmpMainphoto = "";
            if ($("input[name='mainphoto']:checked").val() !== undefined) {
                tmpMainphoto = $("input[name='mainphoto']:checked").val();
            };
            
            $(form).ajaxSubmit({
                target: "#article-msg",
                data: {
                    mainphoto: tmpMainphoto
                },
                dataType: "json",
                beforeSubmit: function(){
                    $(".loadingbox").append(loadingTpl, {
                        icoType: 'clear',
                        loadIcon: '<img src=\"/images/manage/loading002.gif\">',
                        msgHtml: '正在提交数据，请稍候...'
                    });
                    $(".loading").fadeIn(50);
                },
                success: function(data){
                    if (!data.success) {
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: 'fail',
                            loadIcon: '',
                            msgHtml: data.message
                        });
                        $(".loadingbox").fadeIn(50);
                        $(".loadingbox").delay(3000).fadeOut(600);
                    }
                    else {
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: "succ",
                            loadIcon: "",
                            msgHtml: data.message
                        });
                        $(".loadingbox").fadeIn(50);
                        $(".loadingbox").delay(2000).fadeOut(600);
                    }
                    
                }
            });
        },
        rules: {
            title: {
                required: true,
                byteRangeLength: [4, 200]
            },
            columnid: {
                required: false
            },
            specialid: {
                required: false
            },
            postdate: {
                required: true,
                isDate: true
            },
            content: {
                required: true
            }
        },
        messages: {
            title: {
                required: "请填写文章标题",
                byteRangeLength: "文章标题必须在4-200个字符之间(一个中文字算2个字符)"
            },
            columnid: {
                required: "请选择文章所属栏目"
            },
            specialid: {
                required: "请选择文章所属专题"
            },
            postdate: {
                required: "请填写文章发布日期",
                isDate: "文章发布日期格式错误"
            },
            content: {
                required: "文章内容必须填写"
            }
        }
    });
    
    
});
